<template>
  <el-card>
    <UserSubmitForm :form="form" :rules="rules" :formRef="formRef" />
    <el-divider>团购建店照片上传</el-divider>
    <el-card>
      <h4>团购建店照片</h4>
      <!-- 新增：历史交接人展示 -->
      <el-form :inline="true" style="margin-bottom: 16px;">
        <el-form-item label="下一个交接人">
          <el-select v-model="selectedNextOperator" placeholder="请选择交接人" style="width: 200px;">
            <el-option
              v-for="item in employee5List"
              :key="item.employeeId"
              :label="item.name"
              :value="item.account"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div v-for="type in [1,4]" :key="type" style="margin-bottom: 10px;">
        <span>{{ getPhotoTypeLabel(type) }}</span>
        <!-- 平台信息输入 -->
        <el-form :inline="true" style="margin-bottom: 10px;">
          <el-form-item label="平台ID">
            <el-input 
              v-model="platformInfo[type].platformId" 
              placeholder="请输入平台ID"
              style="width: 150px;"
            />
          </el-form-item>
          <el-form-item label="平台账号">
            <el-input 
              v-model="platformInfo[type].platformAccount" 
              placeholder="请输入平台账号"
              style="width: 150px;"
            />
          </el-form-item>
          <el-form-item label="平台密码">
            <el-input 
              v-model="platformInfo[type].platformPassword" 
              placeholder="请输入平台密码"
              style="width: 150px;"
            />
          </el-form-item>
        </el-form>
        <el-upload
          :file-list="Array.isArray(allSetupPhotos[type]) ? allSetupPhotos[type] : []"
          :limit="5"
          :on-change="files => handleAllSetupPhotoChange(type, files)"
          :auto-upload="false"
          :disabled="!canUpload"
          multiple
          accept="image/*"
          list-type="picture-card"
        >
          <el-button :disabled="!canUpload">上传</el-button>
        </el-upload>
      </div>
      <el-tooltip
        :disabled="canUpload && selectedNextOperator && !isUploadingPhotos"
        :content="
          !canUpload ? '请先完善所有必填信息' :
          !selectedNextOperator ? '请选择交接人' :
          isUploadingPhotos ? '正在上传，请稍候' : ''
        "
        placement="top"
      >
        <el-button
          type="primary"
          style="margin-top: 10px;"
          :disabled="!canUpload || !selectedNextOperator || isUploadingPhotos"
          :loading="isUploadingPhotos"
          @click="uploadTuangouPhotos"
        >提交团购建店</el-button>
      </el-tooltip>
    </el-card>
  </el-card>
</template>

<script setup>
import { useRoute, useRouter } from 'vue-router';
import { ref, onMounted, computed } from 'vue';
import UserSubmitForm from '@/components/UserSubmitForm.vue';
import { useUserStore } from '@/store/user';
import { ElMessage } from 'element-plus';

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
const userId = computed(() => userStore.userId);
const storeId = ref(null);

const formRef = ref();
const form = ref({
  storeName: '',
  businessLicenseArr: [],
  foodLicenseArr: [],
  idcardHandArr: [],
  idcardArr: [],
  storeFrontPhotoArr: [],
  storeInsidePhotosArr: [],
  storePhone: '',
  bankCardNumber: '',
  bankPhone: '',
});
const rules = {
  storeName: [{ required: true, message: '请输入门店名称' }],
  businessLicenseArr: [{ required: true, type: 'array', min: 1, message: '请上传营业执照' }],
  foodLicenseArr: [{ required: true, type: 'array', min: 1, message: '请上传食品许可' }],
  idcardHandArr: [{ required: true, type: 'array', min: 2, message: '请上传手持身份证正反面（2张）' }],
  idcardArr: [{ required: true, type: 'array', min: 2, message: '请上传身份证正反面（2张）' }],
  storeFrontPhotoArr: [{ required: true, type: 'array', min: 1, message: '请上传门头照片' }],
  storeInsidePhotosArr: [{ required: true, type: 'array', min: 1, message: '请上传店内环境照片' }],
  storePhone: [{ required: true, message: '请输入联系电话' }],
  bankCardNumber: [{ required: true, message: '请输入银行卡号' }],
  bankPhone: [{ required: true, message: '请输入结算手机号' }],
};

const allSetupPhotos = ref({
  0: [], // 京东外卖
  1: [], // 美团团购
  2: [], // 美团外卖
  3: [], // 饿了么外卖
  4: []  // 抖音团购
});

// 平台信息数据结构
const platformInfo = ref({
  0: { platformId: '', platformAccount: '', platformPassword: '' }, // 京东外卖
  1: { platformId: '', platformAccount: '', platformPassword: '' }, // 美团团购
  2: { platformId: '', platformAccount: '', platformPassword: '' }, // 美团外卖
  3: { platformId: '', platformAccount: '', platformPassword: '' }, // 饿了么外卖
  4: { platformId: '', platformAccount: '', platformPassword: '' }  // 抖音团购
});

const canUpload = computed(() => {
  return (
    form.value.storeName &&
    form.value.businessLicenseArr.length >= 1 &&
    form.value.foodLicenseArr.length >= 1 &&
    form.value.idcardHandArr.length >= 2 &&
    form.value.idcardArr.length >= 2 &&
    form.value.storeFrontPhotoArr.length >= 1 &&
    form.value.storeInsidePhotosArr.length >= 1 &&
    form.value.storePhone &&
    form.value.bankCardNumber &&
    form.value.bankPhone
  );
});

const employee5List = ref([]);
const selectedNextOperator = ref('');
const logsList = ref([]);
const isUploadingPhotos = ref(false); // 上传建店照片按钮loading/禁用

function getPhotoTypeLabel(type) {
  switch (type) {
    case 0: return '京东外卖';
    case 1: return '美团团购';
    case 2: return '美团外卖';
    case 3: return '饿了么外卖';
    case 4: return '抖音团购';
    default: return '';
  }
}

function handleAllSetupPhotoChange(type, files) {
  allSetupPhotos.value[type] = Array.isArray(files) ? files : (files ? [files] : []);
}

// 工具函数：url转File
async function urlToFile(url, filename) {
  const res = await fetch(url);
  const blob = await res.blob();
  return new File([blob], filename, { type: blob.type });
}

// 确认交接人的逻辑
async function confirmNextOperator() {
  if (!selectedNextOperator.value) {
    ElMessage.error('请选择交接人');
    return false;
  }
  // 先更新门店的employee5Id
  const [employee5Id] = selectedNextOperator.value.split(':');
  const resUpdate = await fetch('http://121.43.176.9:8090/api/store/update-employee5', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: `storeId=${storeId.value}&employee5Id=${employee5Id}`
  }).then(r => r.json());
  if (resUpdate.code !== 200) {
    ElMessage.error(resUpdate.msg || '交接人更新失败');
    return false;
  }
  // 再写入交接日志
  const log = {
    storeId: storeId.value,
    submitFrom: userStore.account,
    submitTo: selectedNextOperator.value,
    submitTime: new Date().toISOString(),
    stage: 3 // 新增stage参数，值为3
  };
  const res = await fetch('http://121.43.176.9:8090/api/log/add', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(log)
  }).then(r => r.json());
  if (res.code === 200) {
    ElMessage.success('交接人确认成功');
    return true;
  } else {
    ElMessage.error(res.msg || '交接人确认失败');
    return false;
  }
}

async function uploadTuangouPhotos() {
  if (isUploadingPhotos.value) return;
  isUploadingPhotos.value = true;
  if (!userId.value) {
    ElMessage.error('请先登录');
    isUploadingPhotos.value = false;
    return;
  }

  // 首先确认交接人
  const confirmResult = await confirmNextOperator();
  if (!confirmResult) {
    isUploadingPhotos.value = false;
    return;
  }

  // 构造FormData，支持回显图片
  const fd = new FormData();
  fd.append('userId', userId.value);
  fd.append('storePhone', form.value.storePhone);
  fd.append('bankCardNumber', form.value.bankCardNumber);
  fd.append('bankPhone', form.value.bankPhone);
  fd.append('storeName', form.value.storeName);
  fd.append('storeId', storeId.value);

  // 证件图片支持文件和url
  // 营业执照
  if (form.value.businessLicenseArr[0]?.raw) {
    fd.append('businessLicenseFile', form.value.businessLicenseArr[0].raw);
  } else if (form.value.businessLicenseArr[0]?.url) {
    fd.append('businessLicenseUrl', form.value.businessLicenseArr[0].url);
  }
  // 食品许可
  if (form.value.foodLicenseArr[0]?.raw) {
    fd.append('foodLicenseFile', form.value.foodLicenseArr[0].raw);
  } else if (form.value.foodLicenseArr[0]?.url) {
    fd.append('foodLicenseUrl', form.value.foodLicenseArr[0].url);
  }
  // 手持身份证正反面
  if (form.value.idcardHandArr[0]?.raw) {
    fd.append('idcardHandFrontFile', form.value.idcardHandArr[0].raw);
  } else if (form.value.idcardHandArr[0]?.url) {
    fd.append('idcardHandFrontUrl', form.value.idcardHandArr[0].url);
  }
  if (form.value.idcardHandArr[1]?.raw) {
    fd.append('idcardHandBackFile', form.value.idcardHandArr[1].raw);
  } else if (form.value.idcardHandArr[1]?.url) {
    fd.append('idcardHandBackUrl', form.value.idcardHandArr[1].url);
  }
  // 身份证正反面
  if (form.value.idcardArr[0]?.raw) {
    fd.append('idcardFrontFile', form.value.idcardArr[0].raw);
  } else if (form.value.idcardArr[0]?.url) {
    fd.append('idcardFrontUrl', form.value.idcardArr[0].url);
  }
  if (form.value.idcardArr[1]?.raw) {
    fd.append('idcardBackFile', form.value.idcardArr[1].raw);
  } else if (form.value.idcardArr[1]?.url) {
    fd.append('idcardBackUrl', form.value.idcardArr[1].url);
  }
  // 门头照片
  if (form.value.storeFrontPhotoArr[0]?.raw) {
    fd.append('storeFrontPhotoFile', form.value.storeFrontPhotoArr[0].raw);
  } else if (form.value.storeFrontPhotoArr[0]?.url) {
    fd.append('storeFrontPhotoUrl', form.value.storeFrontPhotoArr[0].url);
  }
  // 店内环境照片（多张）
  let hasRaw = false;
  (form.value.storeInsidePhotosArr || []).forEach((item) => {
    if (item.raw) {
      fd.append('storeInsidePhotoFiles', item.raw);
      hasRaw = true;
    }
  });
  if (!hasRaw && form.value.storeInsidePhotosArr?.length > 0) {
    // 全是历史图片
    const urls = form.value.storeInsidePhotosArr.map(item => item.url).filter(Boolean);
    if (urls.length > 0) {
      fd.append('storeInsidePhotoUrls', urls.join(','));
    }
  }

  const res = await fetch('http://121.43.176.9:8090/api/user-certification/upload-all', {
    method: 'POST',
    body: fd,
  }).then(r => r.json());
  if (res.code !== 200) {
    ElMessage.error(res.msg || '用户资质上传失败');
    isUploadingPhotos.value = false;
    return;
  }
  // 2. 上传建店照片（如果有）
  for (const type of [1, 4]) {
    const files = Array.isArray(allSetupPhotos.value[type]) ? allSetupPhotos.value[type] : [];
    for (let i = 0; i < files.length; i++) {
      const file = files[i];
      // 只上传本地新选的图片
      if (file.raw && file.status !== 'success') {
        const fd2 = new FormData();
        fd2.append('userId', userId.value);
        fd2.append('storeId', storeId.value);
        fd2.append('photoType', type);
        fd2.append('file', file.raw);
        // 添加平台信息
        if (platformInfo.value[type].platformId) {
          fd2.append('platformId', platformInfo.value[type].platformId);
        }
        if (platformInfo.value[type].platformAccount) {
          fd2.append('platformAccount', platformInfo.value[type].platformAccount);
        }
        if (platformInfo.value[type].platformPassword) {
          fd2.append('platformPassword', platformInfo.value[type].platformPassword);
        }
        const res2 = await fetch('http://121.43.176.9:8090/api/store-setup-photos/upload', {
          method: 'POST',
          body: fd2,
        }).then(r => r.json());
        if (res2.code === 200 && res2.data) {
          files[i] = {
            name: file.name,
            url: res2.data,
            status: 'success'
          };
        } else {
          ElMessage.error(res2.msg || '建店图片上传失败');
          isUploadingPhotos.value = false;
          return;
        }
      }
    }
    allSetupPhotos.value[type] = Array.isArray(files) ? files.map(f => ({ ...f })) : [];
  }
  ElMessage.success('团购建店照片上传完成');
  await fetchSetupPhotos();
  // 新增：上传完成后，更新门店状态为0
  if (storeId.value) {
    const res3 = await fetch('http://121.43.176.9:8090/api/store/update-tuangou-status', {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: `storeId=${storeId.value}`
    }).then(r => r.json());
    if (res3.code === 200) {
      ElMessage.success('门店状态已更新为1');
      isUploadingPhotos.value = false;
      router.replace('/user/store-list');
    } else {
      ElMessage.error(res3.msg || '门店状态更新失败');
      isUploadingPhotos.value = false;
    }
  } else {
    isUploadingPhotos.value = false;
  }
}
async function fetchSetupPhotos() {
  if (!storeId.value) return;
  const res = await fetch(`http://121.43.176.9:8090/api/store-setup-photos/by-store/${storeId.value}`).then(r => r.json());
  if (res.code === 200 && Array.isArray(res.data)) {
    // 初始化所有类型
    allSetupPhotos.value = { 0: [], 1: [], 2: [], 3: [], 4: [] };
    res.data.forEach(p => {
      if ([0, 1, 2, 3, 4].includes(p.photoType)) {
        if (!Array.isArray(allSetupPhotos.value[p.photoType])) {
          allSetupPhotos.value[p.photoType] = [];
        }
        allSetupPhotos.value[p.photoType].push({
          name: p.photoPath.split('/').pop(),
          url: p.photoPath,
          status: 'success'
        });
        
        // 填充平台信息
        if (p.platformId || p.platformAccount || p.platformPassword) {
          platformInfo.value[p.photoType] = {
            platformId: p.platformId || '',
            platformAccount: p.platformAccount || '',
            platformPassword: p.platformPassword || ''
          };
        }
      }
    });
  }
}
async function fetchUserCertification() {
  if (!storeId.value) return;
  const res = await fetch(`http://121.43.176.9:8090/api/user-certification/user/${storeId.value}`).then(r => r.json());
  if ((res.code === 0 || res.code === 200) && res.data && res.data.certification) {
    const cert = res.data.certification;
    form.value.storeName = res.data.storeName || cert.storeName || '';
    form.value.businessLicenseArr = cert.businessLicense
        ? [{ name: '营业执照', url: cert.businessLicense, status: 'success' }]
        : [];
    form.value.foodLicenseArr = cert.foodLicense
        ? [{ name: '食品许可', url: cert.foodLicense, status: 'success' }]
        : [];
    // 新增：手持身份证正反面
    form.value.idcardHandArr = [];
    if (cert.idcardHandFront) {
      form.value.idcardHandArr.push({ name: '手持身份证正面', url: cert.idcardHandFront, status: 'success' });
    }
    if (cert.idcardHandBack) {
      form.value.idcardHandArr.push({ name: '手持身份证反面', url: cert.idcardHandBack, status: 'success' });
    }
    // 新增：身份证正反面
    form.value.idcardArr = [];
    if (cert.idcardFront) {
      form.value.idcardArr.push({ name: '身份证正面', url: cert.idcardFront, status: 'success' });
    }
    if (cert.idcardBack) {
      form.value.idcardArr.push({ name: '身份证反面', url: cert.idcardBack, status: 'success' });
    }
    // 新增：门头照片
    form.value.storeFrontPhotoArr = cert.storeFrontPhoto
        ? [{ name: '门头照片', url: cert.storeFrontPhoto, status: 'success' }]
        : [];
    // 新增：店内环境照片（如果是多张，后端需返回数组，这里假设是单张）
    form.value.storeInsidePhotosArr = cert.storeInsidePhotos
        ? [{ name: '店内环境照片', url: cert.storeInsidePhotos, status: 'success' }]
        : [];
    // 其他字段
    form.value.storePhone = cert.storePhone || '';
    form.value.bankCardNumber = cert.bankCardNumber || '';
    form.value.bankPhone = cert.bankPhone || '';
    storeId.value = cert.storeId || null;
  }
}

// 获取员工5列表
async function fetchEmployee5List() {
  const res = await fetch('http://121.43.176.9:8090/api/employee/employee5-list').then(r => r.json());
  if (res.code === 200) {
    employee5List.value = res.data || [];
  } else {
    employee5List.value = [];
  }
}

// 获取当前门店的所有流程日志
async function fetchLogsByStoreId() {
  if (!storeId.value) return;
  const res = await fetch(`http://121.43.176.9:8090/api/log/by-store?storeId=${storeId.value}`).then(r => r.json());
  if (res.code === 200) {
    logsList.value = res.data || [];
    // 找到 submitType 为 1 的最新一条
    const filtered = logsList.value
      .filter(log => log.submitType === 1)
      .sort((a, b) => new Date(b.submitTime) - new Date(a.submitTime));
    if (filtered.length > 0) {
      selectedNextOperator.value = filtered[0].submitTo;
    }
  } else {
    logsList.value = [];
  }
}

// 计算 submitType 为 1 的交接人名字
const handoverNames = computed(() =>
  logsList.value
    .filter(log => log.submitType === 1)
    .map(log => {
      const arr = log.submitTo.split(':');
      return arr.length > 1 ? arr[1] : log.submitTo;
    })
);

const latestHandoverName = computed(() => {
  const filtered = logsList.value
    .filter(log => log.submitType === 1)
    .sort((a, b) => new Date(b.submitTime) - new Date(a.submitTime));
  if (filtered.length === 0) return '';
  const submitTo = filtered[0].submitTo;
  const arr = submitTo.split(':');
  return arr.length > 1 ? arr[1] : submitTo;
});

// 页面加载完成后，获取用户资质和建店照片
onMounted(() => {
  storeId.value = route.query.storeId;
  fetchUserCertification();
  fetchSetupPhotos();
  fetchEmployee5List();
  fetchLogsByStoreId(); // 新增
});
</script>